package com.sm.li.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.sm.li.common.page.PageBean;
import com.sm.li.dto.MenuDTO;
import com.sm.li.dto.RoleDTO;
import com.sm.li.entity.AdminRole;
import com.sm.li.entity.Menu;
import com.sm.li.entity.MenuRole;
import com.sm.li.entity.Role;
import com.sm.li.mapper.AdminRoleMapper;
import com.sm.li.mapper.MenuMapper;
import com.sm.li.mapper.RoleMapper;
import com.sm.li.mapper.RoleMenuMapper;
import com.sm.li.query.RoleQuery;
import com.sm.li.service.RoleService;
import com.sm.li.service.base.impl.BaseServiceImpl;
import com.sm.li.transfer.MenuTransfer;
import com.sm.li.transfer.RoleTransfer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.security.RolesAllowed;
import java.util.*;
import java.util.stream.Collectors;


//两个实体类的属性值互换   BeanUtils jar包     spring提供了BeanUtils
@Service
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleTransfer roleTransfer;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private MenuTransfer menuTransfer;
    @Override
    public PageBean<RoleDTO> searchPage(RoleQuery RoleQuery) {
        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();

        if (!StringUtils.isEmpty(RoleQuery.getRoleName()))
            lambda.like(Role::getRoleName,RoleQuery.getRoleName());

        if (Objects.nonNull(RoleQuery.getStarTime()) && Objects.nonNull(RoleQuery.getEndTime()))
            lambda.between(Role::getCreateTime, RoleQuery.getStarTime(), RoleQuery.getEndTime());

        List<Role> Roles = roleMapper.selectList(lambda);
        PageInfo<Role> pageInfo = new PageInfo<>(Roles);
        List<RoleDTO> RoleDTOS = roleTransfer.toDTO(Roles);
        return PageBean.initData(pageInfo.getTotal(), RoleDTOS);
    }

    @Override
    public int setRoleMenu(Long roleId, List<Long> menuIds) {
        //删除已有权限
        roleMenuMapper.delete(new UpdateWrapper<MenuRole>().lambda().eq(MenuRole::getRoleId,roleId));
        //添加权限
        menuIds.forEach(menuId->roleMenuMapper.insert(new MenuRole(roleId,menuId)));
        return 1;
    }

    @Override
    public List<Long> getMenusByRoleId(Long roleId) {
        List<Long> collect = roleMenuMapper.selectList(new QueryWrapper<MenuRole>().lambda().eq(MenuRole::getRoleId, roleId))
                .stream()
                .map(MenuRole::getMenuId)
                .collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(collect)){
            //返回在权限列表中没有子级的（为解决页面选中部分功能刷新后全选的错误）
            List<Menu> menus = menuMapper.selectBatchIds(collect);
            collect.clear();
            menus.forEach(menu -> {
                if(!menus.stream().anyMatch(item->item.getParentId().equals(menu.getId()))){
                    collect.add(menu.getId());
                }
            });
        }
        return collect;
    }
    //级联删除所有父级子级
    @Override
    public int deleteCascade(Long id) {
        //删除员工和角色中间表数据
        adminRoleMapper.delete(new UpdateWrapper<AdminRole>().lambda().eq(AdminRole::getRoleId,id));
        //删除角色和权限中间表数据
        roleMenuMapper.delete(new UpdateWrapper<MenuRole>().lambda().eq(MenuRole::getRoleId,id));

        return this.deleteById(id);
    }

    @Override
    public int batchCascadeDelete(List<Long> ids) {
        ids.forEach(id->{
            //删除员工和角色中间表数据
            adminRoleMapper.delete(new UpdateWrapper<AdminRole>().lambda().eq(AdminRole::getRoleId,id));
            //删除角色和权限中间表数据
            roleMenuMapper.delete(new UpdateWrapper<MenuRole>().lambda().eq(MenuRole::getRoleId,id));
        });
        return this.deleteBatchIds(ids);
    }

    @Override
    public List<MenuDTO> getMenusByRoleIds(List<Long> roleIds) {
        if (!CollectionUtils.isEmpty(roleIds)){
            Set<Long> collect = roleMenuMapper.selectList(new QueryWrapper<MenuRole>().lambda().in(MenuRole::getRoleId, roleIds)).stream().map(MenuRole::getMenuId).collect(Collectors.toSet());
            List<Menu> menus = menuMapper.selectList(new QueryWrapper<Menu>().lambda().in(Menu::getId, collect));
            return menuTransfer.toDTO(menus);
        }
        return new ArrayList<>();
    }

}
